package com.py.credit.service.impl;

import com.py.credit.dao.DingZhiPluginApiDao;
import com.py.credit.entity.OnlineTimeLogEntity;
import com.py.credit.service.DingZhiPluginApiService;
import com.py.credit.utils.DingZhiConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class DingZhiPluginApiServiceImpl implements DingZhiPluginApiService {

    @Autowired
    private DingZhiPluginApiDao dingZhiPluginApiDao;

    @Override
    public void changeTimeCount(Long userId) {
        OnlineTimeLogEntity logEntity = dingZhiPluginApiDao.selectLogInfo(userId, DingZhiConstant.INTERVAL_MINUTE, DingZhiConstant.LOGIN_STATE_ONLINE);
        if (null != logEntity) {
            dingZhiPluginApiDao.updateLog(logEntity.getId(), logEntity.getTimeCount() + DingZhiConstant.INTERVAL_MINUTE, null);
        }
    }

    @Override
    public void insertLog(Long userId, Long deptId, String username, String realname) {
        OnlineTimeLogEntity logEntity = dingZhiPluginApiDao.selectLogInfo(userId, null, DingZhiConstant.LOGIN_STATE_ONLINE);

        if (null != logEntity) {
            int minute = dingZhiPluginApiDao.selectTimeStampDiff(logEntity.getId());
            if (minute >= DingZhiConstant.MAX_MINUTE) {
                dingZhiPluginApiDao.updateLog(logEntity.getId(), null, DingZhiConstant.LOGIN_STATE_LOGOFF);
                dingZhiPluginApiDao.insertLog(userId, deptId, username, realname);
            } else if (minute >= DingZhiConstant.INTERVAL_MINUTE) {
                dingZhiPluginApiDao.updateLog(logEntity.getId(), logEntity.getTimeCount() + DingZhiConstant.INTERVAL_MINUTE, null);
            }
        } else {
            dingZhiPluginApiDao.insertLog(userId, deptId, username, realname);
        }
    }

    @Override
    public void timeLogout(Long userId) {
        OnlineTimeLogEntity logEntity = dingZhiPluginApiDao.selectLogInfo(userId, null, DingZhiConstant.LOGIN_STATE_ONLINE);

        if (null != logEntity) {
            int minute = dingZhiPluginApiDao.selectTimeStampDiff(logEntity.getId());

            if (minute >= DingZhiConstant.INTERVAL_MINUTE) {
                dingZhiPluginApiDao.updateLog(logEntity.getId(), logEntity.getTimeCount() + DingZhiConstant.INTERVAL_MINUTE, DingZhiConstant.LOGIN_STATE_LOGOFF);
            } else {
                dingZhiPluginApiDao.updateLog(logEntity.getId(), null, DingZhiConstant.LOGIN_STATE_LOGOFF);
            }
        }
    }
}
